<script lang="ts" setup>
//import {excelApi} from "../../../api/axios";
//import {MINIO_HOST} from "../../../const";
import {computed, onMounted, ref, shallowReactive, shallowRef} from "vue";
import router from "../../../router";
import {
  dateFormat,
  myRemove,
  myPage,
  myRemoveBatch,
  getResponseData,
  clazzStatusFormat, elConfirm, isNotNull
} from "../../../util";
import {pageApi, removeApi, removeBatchApi, beginAttendanceApi, updateBatchApi} from "../../../api/attendance.js";
import {listClazzNameApi} from "../../../api/clazz.js";
import MyNav from "../../../components/MyNav.vue";
import MyHead from "../../../components/MyHead.vue";
import MyTable from "../../../components/MyTable.vue";
import MyPager from "../../../components/MyPager.vue";
import MyList from "../../../components/MyList.vue";
import {ElDialog, ElMessage, ElDatePicker} from "element-plus";
import { ElMessageBox } from 'element-plus'
import type { TableInstance } from "element-plus";

// 获取当前课程记录
let course = JSON.parse(sessionStorage.getItem('course'));
// 获取当前排课记录
let schedule = JSON.parse(sessionStorage.getItem('schedule'));
schedule.courseId = course.id
schedule.courseName = course.name
course.mapClazzNameList = ref([])

/* ==================== 分页查询 ==================== */
// 表格数据 + 分页数据
let records = ref();
let pageInfo = shallowReactive({'pageNum': 1, 'pageSize': 1000, 'fn': page});
// 分页查询条件字段：排课名称
let clazzName = shallowRef();
let directionId = shallowRef();
let status = shallowRef();

// 分页函数
async function page(pageNum = pageInfo['pageNum'], pageSize = pageInfo['pageSize']) {
  // 分页基础配置
  let config = {
    'api': beginAttendanceApi,
    'params': {'pageNum': pageNum, 'pageSize': pageSize, 'courseId': course.id, 'scheduleId': schedule.id},
    'records': records,
    'pageInfo': pageInfo
  }

  // 附加为分页条件
  if (status.value !== null) config['params']['status'] = status.value;
  // 发送分页请求
  await myPage(config);
}

/* ==================== 查询要完成本门课学习的班级名称 ==================== */
async function listClazzName() {
  let params = course.mapClazzIds.join(",")
  listClazzNameApi(params).then(res => {
    const data = getResponseData(res)
    Array.prototype.push.apply(course.mapClazzNameList.value, data)
  })
}

/* ==================== 查看详情 ==================== */
// 排课详情抽屉 + 排课详情列表数据
let detailDrawer = shallowRef();
let detailItems = ref();


let statusItems = [
  {'label': '未开始', 'value': 0},
  {'label': '进行中', 'value': 1},
  {'label': '已结束', 'value': 2}
];

function detail(record) {
  detailItems.value = [
    {'label': '开始时间', 'value': record['startTime'], 'format': dateFormat},
    {'label': '结束时间', 'value': record['endTime'], 'format': dateFormat},
    {'label': '学时数', 'value': record['hours']},
    {'label': '状态', 'value': record['status'], format: scheduleStatusFormat, type: 'tag', tagTypeFn: status=>{
        if (status === 0 || status === '0') return 'warning';
        if (status === 1 || status === '1') return 'success';
        if (status === 2 || status === '2') return 'danger';
        return 'default';
      }},
    {'label': '排课描述', 'value': record['info'], 'type': 'card'}
  ];
  detailDrawer.value = true;
}

/* ==================== 批量提交 ==================== */
function batchSubmit() {
  if (myTable.value.getSelectionRows().length == 0) {
    ElMessage.warning('至少修改一条考勤记录')
    return
  }
  // 封装请求参数
  const params = myTable.value.getSelectionRows().map(record => ({
    id: record.id,
    status: record.status,
    note: record.note,
    version: record.version
  }))
  // 提交请求
  updateBatchApi(params).then(res => {
    const data = getResponseData(res)
    if (data) {
      ElMessage.success('提交成功')
      ids.value.splice(0)
      toggleSelection(records.value)
    } else {
      ElMessage.error('提交失败')
    }
  })
}

/* ==================== 单条提交 ==================== */
function submit(row) {
  const params = [row].map(record => ({
    id: record.id,
    status: record.status,
    note: record.note,
    version: record.version
  }))
  // console.log(params)
  updateBatchApi(params).then(res => {
    const data = getResponseData(res)
    if (data) {
      ElMessage.success('提交成功')
      ids.value = ids.value.filter(item => item !== row.id)
      toggleSelection(records.value)
    } else {
      ElMessage.error('提交失败')
    }
  })
}


/* ==================== 批量删除 ==================== */
// 批量删除主键数组
let ids = ref([]);


/* ==================== 打印报表 ==================== */
function excel() {
  // excelApi('/clazz/excel', '排课统计表');
}


/* ==================== 按状态查询 ==================== */
function pageByStatus(val) {
  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (isNotNull(val) || isNotNull(status.value)) {
    status.value = val;
    page();
  }
}

/* ==================== 加载函数 ==================== */
onMounted(() => {
  page()
  listClazzName()
});

function handleDateChange(value) {
  // 处理日期选择变化
  console.log(value);
}

function scheduleStatusFormat(status) {
  if (status === 0 || status === '0') return '缺勤';
  if (status === 1 || status === '1') return '出勤';
  if (status === 2 || status === '2') return '请假';
  if (status === 3 || status === '3') return '迟到';
  if (status === 4 || status === '4') return '早退';
  return '其他';
}

function scheduleStatusTypeFormat(status) {
  if (status === 0 || status === '0') return 'danger';
  if (status === 1 || status === '1') return 'success';
  if (status === 2 || status === '2') return 'warning';
  if (status === 3 || status === '3') return 'warning';
  if (status === 4 || status === '4') return 'warning';
  return '其他';
}

const myTable = ref<TableInstance>()

function handleOptionChange(row, index) {
  // alert(row.id + "/" + index)
  ids.value.push(row.id)
  // 根据传入的ID数组设置表格的选中状态
  toggleSelection(records.value)
}

const toggleSelection = (rows, ignoreSelectable?: boolean) => {
  if (rows) {
    rows.forEach((row) => {
      myTable.value!.toggleRowSelection(
          row,
          ids.value.includes(row.id)
      )
    })
  }
}

const options = [
  { value: 1, label: '出勤', color: '#67C23A'},
  { value: 2, label: '请假', color: '#409EFF' },
  { value: 0, label: '缺勤', color: '#f89898' },
  { value: 3, label: '迟到', color: '#b88230' },
  { value: 4, label: '早退', color: '#b88230' },
]

</script>

<template>

<my-nav :items="[
  {'icon': 'Avatar', 'label': '课程管理'},
  {'icon': 'User', 'label': '进行考勤'},
]"/>
<br/>
<!-- 课程描述 -->
<el-descriptions
    class="margin-top"
    :column="3"
    :size="'small'"
    border
>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <iphone />
        </el-icon>
        课程名称
      </div>
    </template>
    {{ course.name }}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <user />
        </el-icon>
        主讲老师
      </div>
    </template>
    {{course.teacherName}}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <location />
        </el-icon>
        所属阶段
      </div>
    </template>
    {{ course.stageName }}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <tickets />
        </el-icon>
        授课班级
      </div>
    </template>
    <el-tag type="success" v-for="clazzName in course.mapClazzNameList.value" >{{ clazzName }}</el-tag>
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <tickets />
        </el-icon>
        授课年级
      </div>
    </template>
    <el-tag type="primary" >{{ course.mapGradeList }}</el-tag>
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <office-building />
        </el-icon>
        课程备注
      </div>
    </template>
    {{ course.info }}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <office-building />
        </el-icon>
        上课时间
      </div>
    </template>
    {{ schedule.startTime }}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <office-building />
        </el-icon>
        下课时间
      </div>
    </template>
    {{ schedule.endTime }}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <office-building />
        </el-icon>
        课时数
      </div>
    </template>
    {{ schedule.hours }}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <office-building />
        </el-icon>
        COURSE_ID
      </div>
    </template>
    {{ course.id }}
  </el-descriptions-item>
  <el-descriptions-item>
    <template #label>
      <div class="cell-item">
        <el-icon :style="iconStyle">
          <office-building />
        </el-icon>
        SCHEDULE_ID
      </div>
    </template>
    {{ schedule.id }}
  </el-descriptions-item>
</el-descriptions>
<my-head :items="[
  {'type': 'opt', 'span': 5, 'placeholder': '按状态搜索', 'fn': pageByStatus, 'optItems': statusItems},
  {'type': 'batchUpdateBtn', 'btnLabel': '批量提交', 'offset': 1, 'fn': batchSubmit},
]"/>
  <el-table ref="myTable" v-if="records" :data="records" stripe highlight-current-row border style="width: 100%">
    <el-table-column type="selection" :selectable="selectable"  width="55" />
    <el-table-column type="index" label="序号" width="80"/>
    <el-table-column prop="name" label="学生" width="120" />
    <el-table-column prop="clazzName" label="班级" width="120" />
<!--    <el-table-column label="出勤情况" width="180" >
      <template #default="scope">
        <el-tag :type="scheduleStatusTypeFormat(scope.row.status)">{{ scheduleStatusFormat(scope.row.status) }}</el-tag>
      </template>
    </el-table-column>-->
    <el-table-column label="出勤情况" width="380" align="center">
      <template #default="scope">
        <div>
          <el-radio-group v-model="scope.row.status" @change="handleOptionChange(scope.row, scope.$index)">
            <el-radio-button v-for="option in options"  :value="option.value" :label="option.value"  :key="option.value" >
              <span :style="{'color': option.color}">{{ option.label }}</span>
            </el-radio-button>
          </el-radio-group>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="info" label="备注" width="300">
      <template #default="scope">
        <el-input
            v-model="scope.row.note"
            style="width: 240px"
            placeholder="特殊情况请输入"
            clearable
        />
      </template>
    </el-table-column>
    <el-table-column prop="created" label="记录首次创建时间" width="180">

    </el-table-column>
    <el-table-column prop="updated" label="记录最后修改时间" width="180">

    </el-table-column>
    <el-table-column label="操作区" >
      <template #default="scope">
        <el-button class="info-btn" link  type="primary" icon="InfoFilled" @click="submit(scope.row)">提交修改</el-button>
      </template>
    </el-table-column>
  </el-table>

<my-pager v-if="records" :page-info="pageInfo"/>

<el-drawer v-model="detailDrawer" size="30%">
  <my-list title="记录详情" :items="detailItems"/>
</el-drawer>



</template>

<style scoped lang="scss">
  $c: #635d45;
  .el-tag {margin-right: 5px;}
  :deep(.el-radio-button.is-active .el-radio-button__original-radio:not(:disabled)+.el-radio-button__inner) {
    background-color: $c;
    border-color: $c;
    box-shadow: -1px 0 0 0 $c;
    color: var(--el-radio-button-checked-text-color, var(--el-color-white));
  }
</style>